package org.example.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.apache.ibatis.annotations.Param;
import org.example.domain.dto.DTO;
import org.example.domain.dto.ErpDepotItemDTO;
import org.example.domain.po.*;
import org.example.mapper.ErpDepotHeadMapper;
import org.example.mapper.ErpDepotItemMapper;
import org.example.mapper.ErpDepotMapper;
import org.example.service.ErpMaterialCurrentStockService;
import org.example.service.ErpRoleService;
import org.example.service.impl.ErpDepotHeadServiceImpl;
import org.example.service.impl.ErpDepotItemServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

import static org.apache.ibatis.ognl.OgnlOps.multiply;

@RestController
@RequestMapping("/sale")
@Api("/销售管理")
public class ErpDepHeadController {
    @Resource
    private ErpMaterialCurrentStockService erpMaterialCurrentStockService;

    @Autowired
    private ErpDepotHeadServiceImpl erpDepotHeadService;
    @Autowired
    private ErpDepotItemServiceImpl erpDepotItemService;
    @Autowired

    private ErpRoleService roleService;

    @Resource
    ErpDepotHeadServiceImpl erpDepotHeadServiceImpl;

    //分页查询
    @GetMapping("/findByPage")
    public R<Page<ErpDepotHead>> getErpDepotHeadsByPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "3") Integer size,
            String number, String color, String createTime,
            String operTime, String username, String name,
            String status, String remark,String standard, String supName ,@RequestAttribute ErpUser user
    ) {
        Page<ErpDepotHead> page = new Page<>(current, size);
        try {
            page = erpDepotHeadService.selectByExample(page, number, color, createTime, operTime, username, name, status, remark,standard,supName,user.getTenantId());
            ErpRole roleByUserId = roleService.getRoleByUserId(user.getId());
            if(StrUtil.contains("6", roleByUserId.getPriceLimit())){
                List<ErpDepotHead> records = page.getRecords();
                records.forEach(item -> {
                    List<String>names= Arrays.asList("totalPrice","deposit");
                    DTO.shieldPrice(item,names);
                });

            }
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }
    }


    @GetMapping("/findByPagerk")
    public R<Page<ErpDepotHead>>selectByqtrk (
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "3") Integer size

    ) {
        Page<ErpDepotHead> page = new Page<>(current, size);
        try {
            page = erpDepotHeadService.selectByqtrk(page);
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }
    }

    //    删除单个
    @DeleteMapping("/delete/{id}")
    public R delete(@PathVariable("id") Long id) {
        erpDepotHeadService.removeById(id);





        return R.success();
    }

    @DeleteMapping("/deleteck/{id}")
    public R deleteck(@PathVariable("id") Long id) {
        boolean b = erpDepotHeadService.removeById(id);

        if (b) {
            Long sl=erpDepotHeadService.select7(id);//入库单数量
            List<Long> linkIds= erpDepotHeadService.select8(id); // 假设此方法返回 List<Long>


            String count2=erpDepotHeadService.select10(id);
            Long count3=erpDepotHeadService.select5(count2);
            Long count=erpDepotHeadService.select9(linkIds);
            Long sl2=erpDepotHeadService.select7(count3);//订单数量
                if(sl == null){
                    int updateOrderStatus2 = erpDepotHeadService.updateRetail4(count3, "1");
                    System.out.println("销售订单状态更新为完成销售：" + updateOrderStatus2);
                }else{
                    int updateOrderStatus3 = erpDepotHeadService.updateRetail4(count3,"3");
                    System.out.println("销售订单状态更新为部分销售：" + updateOrderStatus3);


                return R.success();
            }
        }





        return R.success();
    }
    //    批量删除
    @DeleteMapping("/delete")
    public R deleteBatch(@RequestBody List<Long> ids) {
        for (Long id : ids) {
            erpDepotHeadService.removeById(id);
        }
        return R.success();
    }

    @GetMapping("/heftid")
    public R<List<ErpDepotHead>>finid(Long headerId) {
        List<ErpDepotHead> erpDepotHeads = erpDepotHeadService.findherfid(headerId);
        return R.success(erpDepotHeads);
    }
    //修改
    @PutMapping("/update")
    public R update(@RequestBody ErpDepotHead erpDepotHead) {
        try {
            erpDepotHeadService.updateById(erpDepotHead);
            return R.success();
        } catch (Exception e) {
            return R.fail("更新失败：" + e.getMessage());
        }
    }

    //    新增
    @PostMapping("/insert")
    public R add(@RequestBody DepotRequest depotRequest, @RequestAttribute ErpUser user) {
        ErpDepotHead erpDepotHead = depotRequest.getErpDepotHead();
        List<ErpDepotItem> erpDepotItems = depotRequest.getErpDepotItems();

        erpDepotHead.setCreateTime(new Date());
        erpDepotHead.setOperTime(new Date());
        erpDepotHead.setTenantId(user.getTenantId());
        erpDepotHead.setDefaultNumber(erpDepotHead.getNumber());

        int insert = erpDepotHeadService.insertdd(erpDepotHead);
        if (insert > 0) {
            Long headerId = erpDepotHeadService.finbyid(erpDepotHead.getNumber());

            for (ErpDepotItem item : erpDepotItems) {
                item.setTenantId(user.getTenantId());

                item.setHeaderId(headerId);
                ErpDepotItemDTO erpDepotItem = BeanUtil.copyProperties(item, ErpDepotItemDTO.class);
                erpDepotItemService.insert(erpDepotItem);
            }
        }

        return R.success();
    }

    @PostMapping("/insertck")
    public R insertck(@RequestBody DepotRequest depotRequest, @RequestAttribute ErpUser user) {
        ErpDepotHead erpDepotHead = depotRequest.getErpDepotHead();
        List<ErpDepotItem> erpDepotItems = depotRequest.getErpDepotItems();
        erpDepotHead.setTenantId(user.getTenantId());
        erpDepotHead.setCreateTime(new Date());
        erpDepotHead.setOperTime(new Date());
        erpDepotHead.setDefaultNumber(erpDepotHead.getNumber());

        // 保存出库头信息
        int insert = erpDepotHeadService.insertck(erpDepotHead);

        if (insert>0) {

            // 获取订单的 ID
            Long headId = erpDepotHeadService.lookByHeaderId(erpDepotHead.getNumber());
            Long sl=erpDepotHeadService.select7(headId);

            List<Long> linkIds= erpDepotHeadService.select8(headId); // 假设此方法返回 List<Long>


            String linkNumber = erpDepotHead.getLinkNumber(); // 销售订单号

            // 查询出库副表商品信息总条数
            Long linkid = erpDepotHeadService.lookByHeaderId(linkNumber);
            List<Long> itemid=erpDepotItemService.lookByitemidnumvber(linkNumber);
            // 创建集合以存储所有的linkId
            List<Long> allLinkIds = new ArrayList<>();

            // 保存出库条目并检查销售订单状态
            for (ErpDepotItem item : erpDepotItems) {
                item.setHeaderId(headId);
                item.setTenantId(user.getTenantId());
                ErpDepotItemDTO erpDepotItemDTO = BeanUtil.copyProperties(item, ErpDepotItemDTO.class);
                erpDepotItemService.insert(erpDepotItemDTO);
                erpMaterialCurrentStockService.updateStock(item.getMaterialId(),item.getDepotId(),item.getOperNumber().negate(),item.getTenantId());
                // 将当前item的linkId添加到集合中
                List<Long> linid = Collections.singletonList(item.getLinkId());
                if (linid != null) {
                    allLinkIds.addAll(linid);
                }
            }

            Long count=erpDepotHeadService.select9(linkIds);



            // 根据出库数量与销售订单数量判断状态并更新
            if (sl==count) { // 完成所有商品的出库
                int updateOrderStatus2 = erpDepotHeadService.updateOrderStatus2(erpDepotHead.getLinkNumber());
                System.out.println("销售订单状态更新为完成销售：" + updateOrderStatus2);
            } else { // 部分商品已出库
                int updateOrderStatus3 = erpDepotHeadService.updateOrderStatus3(erpDepotHead.getLinkNumber());
                System.out.println("销售订单状态更新为部分销售：" + updateOrderStatus3);
            }
        }

        return R.success();
    }

    @PostMapping("/insertck2")
    public R insertck2(@RequestBody DepotRequest depotRequest, @RequestAttribute ErpUser user) {
        ErpDepotHead erpDepotHead = depotRequest.getErpDepotHead();
        List<ErpDepotItem> erpDepotItems = depotRequest.getErpDepotItems();
        erpDepotHead.setTenantId(user.getTenantId());
        erpDepotHead.setCreateTime(new Date());
        erpDepotHead.setOperTime(new Date());
        erpDepotHead.setDefaultNumber(erpDepotHead.getNumber());
        // 保存出库头信息
        int insert = erpDepotHeadService.insertck(erpDepotHead);

        if (insert>0) {

            Long headId =  erpDepotHeadService.lookByHeaderId(erpDepotHead.getNumber());
            for (ErpDepotItem item : erpDepotItems) {
                item.setHeaderId(headId);
                item.setTenantId(user.getTenantId());
                ErpDepotItemDTO erpDepotItemDTO = BeanUtil.copyProperties(item, ErpDepotItemDTO.class);
                erpDepotItemService.insert(erpDepotItemDTO);
                erpMaterialCurrentStockService.updateStock(item.getMaterialId(),item.getDepotId(),item.getOperNumber(),item.getTenantId());
            }
        }
        return R.success();
    }

    //批量修改状态
    @PutMapping("/updatestatus")
    public R updatestatus(@RequestBody UpdateStatusRequest request) {
        if (request.getIds() == null || request.getIds().isEmpty()) {
            return R.fail("ID 列表不能为空");
        }

        try {
//            erpDepotHeadService.updateOrderStatus(request.getIds(), request.getStatus());
            boolean update = erpDepotHeadService.update(request.getIds(), request.getStatus());
            return R.success();
        } catch (Exception e) {
            return R.fail("批量更新失败：" + e.getMessage());
        }
    }


    @PutMapping("/updateck")
    public R updateck(@RequestBody DepotRequest depotRequest, @RequestParam String number) {
        // 获取头部和明细信息
        ErpDepotHead erpDepotHead = depotRequest.getErpDepotHead();
        List<ErpDepotItem> erpDepotItems = depotRequest.getErpDepotItems();



        int headUpdateCount = erpDepotHeadService.updateDepotHead(erpDepotHead,number);
        if (headUpdateCount > 0) {

            Long headerId = erpDepotHeadService.lookByHeaderId(number);

            for (ErpDepotItem item : erpDepotItems) {
                boolean itemUpdateCount = erpDepotItemService.updateById(item);

                if (!itemUpdateCount) {
                    return R.fail("子表更新失败");
                }
            }
        } else {
            return R.fail("头部更新失败");
        }

        return R.success("更新成功");
    }







    @GetMapping("/findByPageOderck")
    public R<Page<ErpDepotHead>> getErpDepotHeadsByPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "2") Integer size,
            String number, String accountname,String color, String createTime,
            String operTime, String username, String supName,
            String status, String remark,String standard,String changeAmount,String supplier,
            String dname,String debt,@RequestAttribute ErpUser user
    ){
        Page<ErpDepotHead> page = new Page<>(current, size);
        try {

            page = erpDepotHeadService.selectOderck(page, number,accountname, color, createTime, operTime, username, supName, status, remark,standard,supplier,changeAmount,dname,debt,user.getTenantId());
            ErpRole roleByUserId = roleService.getRoleByUserId(user.getId());
            if(StrUtil.contains("6", roleByUserId.getPriceLimit())){
                page.getRecords().forEach(item -> {
                    List<String>names= Arrays.asList("totalPrice","deposit");
                    DTO.shieldPrice(item,names);
                });

            }
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }
    }



    @GetMapping("/findByPageOderth")
    public R<Page<ErpDepotHead>> selectOderth(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "2") Integer size,
            String number,String discountLastMoney ,String accountname,String color, String createTime,
            String operTime, String username, String supName,
            String status, String remark,String standard,String changeAmount,String supplier,
            String dname,String debt,@RequestAttribute ErpUser user
    ){
        Page<ErpDepotHead> page = new Page<>(current, size);
        try {

            page = erpDepotHeadService.selectOderth(page, number,discountLastMoney,accountname, color, createTime, operTime, username, supName, status, remark,standard,supplier,changeAmount,dname,debt,user.getTenantId());
            ErpRole roleByUserId = roleService.getRoleByUserId(user.getId());
            if(StrUtil.contains("6", roleByUserId.getPriceLimit())){
                page.getRecords().forEach(item -> {
                    List<String>names= Arrays.asList("totalPrice","deposit");
                    DTO.shieldPrice(item,names);
                });

            }
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }
    }


    @GetMapping("/findByPageAssociateorder")
    public R<Page<ErpDepotHead>> selectOut(@RequestParam(defaultValue = "1") Integer current,
                                           @RequestParam(defaultValue = "2") Integer size, String number, String createTime,
                                           String operTime,String standard,Long id,String subType,@RequestAttribute("user") ErpUser user){
        Page<ErpDepotHead> page=new Page<>(current,size);
        try {
            page=erpDepotHeadService.selectOut(page,number,createTime,operTime,standard,id,subType,user.getTenantId());
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }

    }
    @GetMapping("/findByPageAssociateorder2")
    public R<Page<ErpDepotHead>> selectOut2(@RequestParam(defaultValue = "1") Integer current,
                                           @RequestParam(defaultValue = "2") Integer size, String number, String createTime,
                                           String operTime,String standard,Long organId){
        Page<ErpDepotHead> page=new Page<>(current,size);
        try {
            page=erpDepotHeadService.selectOut2(page,number,createTime,operTime,standard,organId);
            return R.success(page);
        } catch (Exception e) {
            return R.fail("查询失败：" + e.getMessage());
        }

    }
    @GetMapping("/selectByPrimaryKey")
    public R<List<ErpDepotItem>> selectByPrimaryKey(@Param("headerId")Long headerId){
        List<ErpDepotItem> erpDepotItems=erpDepotItemService.selectByPrimaryKey(headerId);
        return R.success(erpDepotItems);
    }
    
    @GetMapping("/lookByitemid")
    public R<List<ErpDepotItem>> lookByitemid(@RequestParam("headerId") Long headerId) {
        List<ErpDepotItem> erpDepotItems = erpDepotItemService.lookByitemid(headerId);
        return R.success(erpDepotItems);
    }
    @PostMapping("insertdepot")
    public R insertdepot(@RequestBody DepotRequest request, @RequestAttribute("user") ErpUser user){
        ErpDepotHead erpDepotHead = request.getErpDepotHead();
        List<ErpDepotItem> erpDepotItems = request.getErpDepotItems();

        erpDepotHead.setTenantId(user.getTenantId());
        erpDepotHead.setCreateTime(new Date());
        erpDepotHead.setOperTime(new Date());
        erpDepotHead.setDefaultNumber(erpDepotHead.getNumber());

        int insert = erpDepotHeadService.deprotinsert(erpDepotHead);
        if (insert > 0) {
            Long headerId = erpDepotHeadService.finbyid(erpDepotHead.getNumber());

            for (ErpDepotItem item : erpDepotItems) {
                item.setTenantId(user.getTenantId());
                item.setHeaderId(headerId);
                ErpDepotItemDTO erpDepotItemDTO = BeanUtil.copyProperties(item, ErpDepotItemDTO.class);
                erpDepotItemService.insertdepot(erpDepotItemDTO);
                // 调入仓库新增库存
                erpMaterialCurrentStockService.updateStock(item.getMaterialId(), item.getDepotId(), item.getOperNumber(), item.getTenantId());
            }
        }
        return R.success();
    }

    @PostMapping("insertdepottwo")
    public R insertdepottwo(@RequestBody DepotRequest request, @RequestAttribute("user") ErpUser user){
        ErpDepotHead erpDepotHead = request.getErpDepotHead();
        List<ErpDepotItem> erpDepotItems = request.getErpDepotItems();
        erpDepotHead.setTenantId(user.getTenantId());
        erpDepotHead.setCreateTime(new Date());
        erpDepotHead.setOperTime(new Date());
        erpDepotHead.setDefaultNumber(erpDepotHead.getNumber());

        int insert = erpDepotHeadService.depotinserttwo(erpDepotHead);
        if (insert > 0) {
            Long headerId = erpDepotHeadService.finbyid(erpDepotHead.getNumber());

            for (ErpDepotItem item : erpDepotItems) {
                item.setTenantId(user.getTenantId());
                item.setHeaderId(headerId);
                ErpDepotItemDTO erpDepotItemDTO = BeanUtil.copyProperties(item, ErpDepotItemDTO.class);
                erpDepotItemService.insertdepot(erpDepotItemDTO);
                // 调入仓库新增库存
                erpMaterialCurrentStockService.updateStock(item.getMaterialId(), item.getAnotherDepotId(), item.getOperNumber(), item.getTenantId());
                // 调出仓库减少库存
                erpMaterialCurrentStockService.updateStock(item.getMaterialId(), item.getDepotId(), item.getOperNumber().negate(), item.getTenantId());
            }
        }
        return R.success();
    }

    @PostMapping("insertdepotdb")
    @Transactional
    public R insertdepotdb(@RequestBody DepotRequest request, @RequestAttribute("user") ErpUser user){
        ErpDepotHead erpDepotHead = request.getErpDepotHead();
        List<ErpDepotItem> erpDepotItems = request.getErpDepotItems();
        erpDepotHead.setTenantId(user.getTenantId());
        erpDepotHead.setCreator(user.getId());
        erpDepotHead.setCreateTime(new Date());
        erpDepotHead.setOperTime(new Date());
        erpDepotHead.setDefaultNumber(erpDepotHead.getNumber());
        int insert = erpDepotHeadService.depotinsertdb(erpDepotHead);
        if (insert > 0) {
            Long headerId = erpDepotHeadService.finbyid(erpDepotHead.getNumber());
            for (ErpDepotItem item : erpDepotItems) {
                item.setHeaderId(headerId);
                item.setTenantId(user.getTenantId());
                ErpDepotItemDTO erpDepotItemDTO = BeanUtil.copyProperties(item, ErpDepotItemDTO.class);
                erpDepotItemService.insertdepot(erpDepotItemDTO);
                // 调入仓库新增库存
                erpMaterialCurrentStockService.updateStock(item.getMaterialId(), item.getAnotherDepotId(), item.getOperNumber(), item.getTenantId());
                // 调出仓库减少库存
                erpMaterialCurrentStockService.updateStock(item.getMaterialId(), item.getDepotId(), item.getOperNumber().negate(), item.getTenantId());
            }
        }
        return R.success();
    }
}
